<template >
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>添加商品</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图>栅格系统包含搜索 -->
		<el-card class="box-card">
			<!-- 提示区 -->
			<el-alert title="添加商品信息" type="info" center show-icon></el-alert>
			<!-- 步骤条 -->
			<!-- 这里的active需要一个数字类型的索引 -->
			<el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
				<el-step title="基本信息"></el-step>
				<el-step title="商品参数"></el-step>
				<el-step title="商品属性"></el-step>
				<el-step title="商品图片"></el-step>
				<el-step title="商品内容"></el-step>
				<el-step title="完成"></el-step>
			</el-steps>

			<!-- tab栏区域 -->
			<el-form
				:model="addForm"
				:rules="addFormRules"
				ref="addFormRef"
				label-width="100px"
				label-position="top"
			>
				<!-- 这里的v-model需要字符串,官方定义name来关联 -->
				<!-- name	与选项卡绑定值 value 对应的标识符，表示选项卡别名 -->
				<el-tabs
					v-model="activeIndex"
					:tab-position="'left'"
					:before-leave="beforeTabLeave"
					@tab-click="tabClicked"
				>
					<el-tab-pane label="基本信息" name="0">
						<el-form-item label="商品名称" prop="goods_name">
							<el-input v-model="addForm.goods_name"></el-input>
						</el-form-item>
						<el-form-item label="商品价格" prop="goods_price">
							<el-input v-model="addForm.goods_price" type="number"></el-input>
						</el-form-item>
						<el-form-item label="商品重量" prop="goods_weight">
							<el-input v-model="addForm.goods_weight" type="number"></el-input>
						</el-form-item>
						<el-form-item label="商品数量" prop="goods_number">
							<el-input v-model="addForm.goods_number" type="number"></el-input>
						</el-form-item>
						<el-form-item label="商品分类" prop="goods_cat">
							<el-cascader
								v-model="addForm.goods_cat"
								:options="cateList"
								:props="cateProps"
								@change="handleChange"
							></el-cascader>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品参数" name="1">
						<el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
							<!-- 复选框组 -->
							<el-checkbox-group v-model="item.attr_vals">
								<el-checkbox :label="item" v-for="(item,index) in item.attr_vals" :key="index" border></el-checkbox>
							</el-checkbox-group>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品属性" name="2">
						<el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
							<!-- 复选框组 -->
							<el-input v-model="item.attr_vals"></el-input>
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="商品图片" name="3">
						<!-- 图片上传 -->
						<el-upload
							class="upload-demo"
							:action="actionURL"
							:on-preview="handlePreview"
							:on-remove="handleRemove"
							list-type="picture"
							:headers="headerObj"
							:on-success="picSuccess"
						>
							<el-button size="small" type="primary">点击上传</el-button>
							<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
						</el-upload>
					</el-tab-pane>
					<el-tab-pane label="商品内容" name="4">
						<quill-editor v-model="addForm.goods_introduce"></quill-editor>
						<el-button type="primary" @click="add">添加商品</el-button>
					</el-tab-pane>
				</el-tabs>
			</el-form>
		</el-card>

		<!-- 图片预览 -->
		<el-dialog title="提示" :visible.sync="previewVisible" width="50%" class="previewPic">
			<img :src="this.previewPath" alt />
		</el-dialog>
	</div>
</template>

<script>
	import _ from "lodash";
	export default {
		data() {
			return {
				// 获取所有商品分类的数据
				activeIndex: "0",
				addForm: {
					goods_name: "",
					goods_price: "",
					goods_weight: "",
					goods_number: "",
					// 商品所属分类数组
					goods_cat: [],
					// 图片的数组
					pics: [],
					// 商品描述
					goods_introduce: "",
					// 商品的参数（数组），包含 动态参数 和 静态属性
					attrs: []
				},
				addFormRules: {
					goods_name: [
						{ required: true, message: "请输入商品名称", trigger: "blur" }
					],
					goods_price: [
						{ required: true, message: "请输入商品价格", trigger: "blur" }
					],
					goods_weight: [
						{ required: true, message: "请输入商品重量", trigger: "blur" }
					],
					goods_number: [
						{ required: true, message: "请输入商品数量", trigger: "blur" }
					],
					goods_cat: [
						{ required: true, message: "请选择商品分类", trigger: "blur" }
					]
				},
				cateList: [],
				cateProps: {
					label: "cat_name",
					value: "cat_id",
					children: "children",
					expandTrigger: "hover"
				},
				manyTableData: [],
				onlyTableData: [],
				// 图片的请求地址接口文档中有介绍
				actionURL: "http://127.0.0.1:8888/api/private/v1/upload",
				// 图片上传组件并不是用axios,所以请求头中没有token,上传不成功,这里设置headers请求头对象
				headerObj: {
					Authorization: window.sessionStorage.getItem("token")
				},
				previewPath: "",
				previewVisible: false
			};
		},
		created() {
			this.getCateList();
		},
		methods: {
			async getCateList() {
				let { data: res } = await this.$http.get("categories");
				// console.log(res.data);
				if (res.meta.status !== 200)
					return this.$message.error("获取商品列表失败");
				this.cateList = res.data;
			},
			handleChange() {
				// console.log(this.addForm.goods_cat);
				if (this.addForm.goods_cat.length !== 3) {
					this.addForm.goods_cat = [];
				}
			},
			// before-leave	切换标签之前的钩子，若返回 false
			// 或者返回 Promise 且被 reject，则阻止切换。
			// Function(activeName, oldActiveName)
			beforeTabLeave(activeName, oldActiveName) {
				// console.log("即将离开的标签页名字+" + oldActiveName);
				// console.log("即将进入的标签页名字+" + activeName);
				// return false;
				if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
					this.$message.error("请先选择商品分类");
					return false;
				}
			},
			async tabClicked() {
				// 用于判断当前高亮的索引页
				// console.log(this.activeIndex);
				if (this.activeIndex == "1") {
					let { data: res } = await this.$http.get(
						`categories/${this.cateId}/attributes`,
						{ params: { sel: "many" } }
					);
					// console.log(res.data);
					if (res.meta.status !== 200)
						return this.$message.error("获取动态参数列表失败");
					res.data.forEach(item => {
						item.attr_vals =
							item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
					});
					this.manyTableData = res.data;
					console.log(this.manyTableData);
				} else if (this.activeIndex == "2") {
					let { data: res } = await this.$http.get(
						`categories/${this.cateId}/attributes`,
						{ params: { sel: "only" } }
					);
					// console.log(res.data);
					if (res.meta.status !== 200)
						return this.$message.error("获取动态参数列表失败");
					// res.data.forEach(item => {
					// 	item.attr_vals =
					// 		item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
					// });
					this.onlyTableData = res.data;
					console.log(this.onlyTableData);
				}
			},
			// 处理图片预览效果
			handlePreview(file) {
				// 返回当前点击图片的地址对象
				// console.log(file);
				this.previewPath = file.response.data.url;
				this.previewVisible = true;
			},
			// 处理移除图片的操作
			handleRemove(file) {
				// 默认返回输出对象
				// console.log(file);
				// 1. 获取将要删除的图片的临时路径
				let filePath = file.response.data.tmp_path;
				// 2.从pics数组中,找到这个图片对应的索引值
				let index = this.addForm.pics.findIndex(item => item.pic === filePath);
				// 3.调用数组的 splice 方法, 把图片信息对象,从pics数组中移除
				this.addForm.pics.splice(index, 1);
				console.log(this.addFrom);
			},
			// 监听图片上传成功的事件
			picSuccess(response) {
				console.log(response);
				// 图片上传的钩子函数中,三个形参的第一个是response反馈上传结果
				if (response.meta.status !== 200)
					return this.$message.error("图片上传失败");
				// 1.拼接得到一个图片信息对象
				let picInfo = { pic: response.data.tmp_path };
				// 2.将图片信息对象,push到pics数组中
				this.addForm.pics.push(picInfo);
				console.log(this.addForm);
			},
			add() {
				this.$refs.addFormRef.validate(async valid => {
					if (!valid) return this.$message.error("请填写表单");
					console.log(this.addForm);
					// 因为addForm.goods_cat被数据绑定,并确定数据类型是数组
					// 这里根据接口文档,要求其为用 , 隔开的字符串
					// 所以,要对其进行处理,如果直接用join,改变其数据类型,变会报错
					// 所以, 引入一个新的插件,lodash可以深拷贝一个addForm对象,赋值给form
					// 这样操作form就没有问题了
					let form = _.cloneDeep(this.addForm);
					form.goods_cat = form.goods_cat.join(",");

					// 另外，需要处理另外一个提交参数 attrs
					// 1处理动态参数
					this.manyTableData.forEach(item => {
						let newInfo = {
							attr_id: item.attr_id,
							attr_value: item.attr_vals.join(",")
						};
						this.addForm.attrs.push(newInfo);
					});
					// 2.处理静态参数
					this.onlyTableData.forEach(item => {
						let newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals };
						this.addForm.attrs.push(newInfo);
					});
					// 3.将处理好的属性,赋值给要提交的form
					form.attrs = this.addForm.attrs;
					console.log(form);
					let { data: res } = await this.$http.post("goods", form);
					console.log(res);
				});
			}
		},
		computed: {
			cateId() {
				if (this.addForm.goods_cat.length == 3) {
					return this.addForm.goods_cat[2];
				}
				return null;
			}
		}
	};
</script>

<style lang="less" scoped>
	.el-steps {
		margin: 15px 0;
	}
	.previewPic img {
		width: 100%;
	}
</style>